# -*- coding: utf-8 -*-
# 利用SMTP，向qq邮箱发送邮件，包括正文文本+图片+表格，附件图片+表格；
# python sendMailDf.py
import os
import sys
import time
import traceback

import pandas as pd
import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QLabel, QMessageBox


def runMail():
    # 设置初始化参数
    mail_user = ""  # 邮箱登录名，此处使用QQ邮箱，填写QQ号即可，不用带@qq.com
    mail_pass = ""  # QQ邮箱授权码
    column_to_text = 0
    sender = ""  # 发件人
    receivers = []  # 收件人列表，list形式
    chaosongs = []  # 抄送人列表，list形式
    misongs = []  # 密送列表，list形式
    subject = ""
    htmlFile = ""
    filepaths = []

    if len(sys.argv) > 1:
        config_file_path = sys.argv[1]
    else:
        config_file_path = "邮件分发设置.xlsx"

    dtypes1 = {'配置名称': str, '邮箱服务器': str, '邮箱服务端口': str, column_to_text: str, 'SSL加密': str,
               '发件人邮箱': str, '发件人显示名': str, '登录密码': str}
    dtypes2 = {'发件配置': str, '收件人': str, '抄送': str, column_to_text: str, '密送': str, '邮件主题': str,
               '邮件正文': str, '附件路径': str, '发送选项': str}

    # try:
    df = pd.read_excel(config_file_path, header=0, dtype=dtypes1, sheet_name='参数配置')
    df2 = pd.read_excel(config_file_path, header=0, dtype=dtypes2, sheet_name='邮件分发')
    for index, row in df.iterrows():
        mail_host = row["邮箱服务器"]
        mail_user = row["发件人邮箱"]
        mail_pass = row["登录密码"]
        print(f"Row: {row['邮箱服务器']}, {row['发件人邮箱']},{row['登录密码']}")
    for index, row in df2.iterrows():
        receivers = str(row['收件人']).split()
        chaosongs = str(row['抄送']).split()
        misongs = str(row['密送']).split()
        subject = row['邮件主题']
        htmlFile = row['邮件正文']
        filepaths = str(row['附件路径']).split()
        print(f"Row: {receivers}, {chaosongs},{misongs}, {subject}, {htmlFile}, {filepaths}")

    sender = mail_user  # 发件人
    # 设置邮件体对象
    msg = MIMEMultipart()  # 邮件体对象，此处可加入参数， 具体可百度
    msg['subject'] = Header(subject, 'utf-8')  # 加入邮件主题
    msg['From'] = "{}".format(sender)  # 加入邮件发送人
    msg['To'] = ",".join(receivers)  # 加入邮件接收人
    msg['Cc'] = ",".join(chaosongs)  # 加入邮件抄送人，如无，可注释掉


    # 网页内容，有链接，插入图片
    data_link = 'http://app01.cdps.shrcb:8001/CDPS/index.html'
    htmlFile = htmlFile.format(link=data_link)
    htmlApart = MIMEText(htmlFile, 'html')

    # 在正文中显示图片
    # imageFile = "ym.jpg"
    # imageApart = MIMEImage(open(imageFile, 'rb').read(), imageFile.split('.')[-1])
    # imageApart.add_header('Content-ID', '<0>')
    # msg.attach(imageApart)
    msg.attach(htmlApart)

    # 加入多个附件
    for i in filepaths:
        try:
            attFile = MIMEApplication(open(i, 'rb').read())
            attFile.add_header('Content-Disposition', 'attachment', filename=i)
            msg.attach(attFile)
        except FileNotFoundError:
            continue

    # 发送邮件，参数设置mail.shrcb
    try:
        sftp_obj = smtplib.SMTP(host=mail_host, port=25)
        sftp_obj.login(mail_user, mail_pass)
        sftp_obj.sendmail(sender, receivers, msg.as_string())
        sftp_obj.quit()
        sftp_obj.close()
        print('\nThe email has been sent successfully')
        del msg
        return True
    except Exception as e:
        print(e)
        return False



class win(QWidget):
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout()
        openConfig = QPushButton("打开邮件配置", self)
        # openConfig.setText()
        openTemplate = QPushButton("打开配置模板", self)
        # openTemplate.setText()
        startButton = QPushButton("运行", self)

        layout.addWidget(QLabel("配置模板仅用于参考，请勿修改"))
        layout.addWidget(openConfig)
        layout.addWidget(openTemplate)
        # layout.addStretch()
        layout.addWidget(startButton)

        self.setLayout(layout)
        openConfig.clicked.connect(self.openConfig)
        openTemplate.clicked.connect(self.openTemplate)
        startButton.clicked.connect(self.start)

    def openConfig(self):
        if len(sys.argv) > 1:
            config_file_path = sys.argv[1]
        else:
            config_file_path = "邮件分发设置.xlsx"
        print(config_file_path)
        # print(len(sys.argv))
        os.system(config_file_path)
        pass

    def openTemplate(self):
        if len(sys.argv) > 1:
            config_file_path = sys.argv[2]
        else:
            config_file_path = "邮件分发设置_模板.xlsx"
        print(config_file_path)
        os.system(config_file_path)

    def start(self):
        res = runMail()

        if res:
            QMessageBox.information(self,"", "邮件成功发送！")
        else:
            QMessageBox.critical(self,"", "邮件发送失败，请查看后台日志！")

# 设置全局异常钩子


if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = win()
    main.show()
    sys.exit(app.exec())
    # sys.excepthook = handle_exception

    # runMail()